#include "mainwindow.h"
#include <QtGui>
#include "ui_mainwindow.h"

#include <qdebug.h>
#include <iostream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //constants
    KEY_PATH = "path";
    PICS_PATH = "picsPath";
    GRAPHICS_PATH = "graphicsPath";
    KEY_INTERVAL = "interval";
    KEY_THREADS = "threads";
    KEY_ADVANCED = "advanced";

    Z_POINTS = "z_points";
    X_POINTS = "x_points";
    ASPECT_RATIO = "aspect_ratio";
    TIME_STEPS_MAX = "timax";
    OUTPUT_STEP = "stp_ascii";
    RAYLEIGH = "Ra";
    RAYLEIGH_H = "RaH";
    VISC_CONTRAST_T = "eT";
    T_REF = "Tref";
    VISC_CONTRAST_Z = "ez";
    Z_REF = "Zref";
    RESTART = "restart";

    yaccSettings = new YACCSettings();
    startingDir =  QDir::currentPath();

    readConfig();

    QFile::copy(yaccDir +"/yacc.inp", yaccDir +"/yacc.easy");
    QFile::copy(yaccDir +"/yacc.inp", yaccDir +"/yacc.advanced");

    yaccSettings->setFile(yaccDir + "/yacc.easy");
    values = yaccSettings->read();

    paused = false;
    firstrun = false;
    isRunning = false;
    varrestart = false;
    yaccfinished = false;
    numberofPics = 0;
    numberofPicsOld = 0;
    numberofFiles = 0;
    numberofCheckFiles = 0;
    numberofcurrentFiles = 0;
    previousDisplayedPic = " ";
    finished_processes = 0;
    finished_fields[0] = false;
    finished_fields[1] = false;
    finished_fields[2] = false;
    finished_fields[3] = false;
    finished_fields[4] = false;
    picIter = NULL;
    fileIter = NULL;
    checkIter = NULL;
    fileold = " ";
    processes = NULL;
    computed = 1;
    running_Processes = 0;

    lastclicked = false;

    ui->label->setStyleSheet("QLabel { background-color : white}");
    ui->label->setAlignment(Qt::AlignCenter);


    // mirror in eigenschaften beenden
    if (advanced == 0) {
        ui->comboBox->hide();
    }
    else {
        ui->comboBox->show();
    }

    ui->textEdit->hide();

    setupStatusBar();
    setupButtons();

    setupView();

    setupPictureIterator();
    showPic();

    cTimer = setupComputing(50);
    zaehler = 0;
    pTimer = setupTimer(interval);
}

MainWindow::~MainWindow()
{
    delete processes;
    delete ui;
}

void MainWindow::setupStatusBar()
{
    statusMessageLabel = new QLabel("Bitte starten");
    statusMessageLabel->setAlignment(Qt::AlignHCenter);
    statusMessageLabel->setMinimumSize(statusMessageLabel->sizeHint());

    statusBar()->addWidget(statusMessageLabel);

}

QTimer* MainWindow::setupTimer(int i)
{
    QTimer *timer = new QTimer(this);
    timer->setInterval(i);
    connect(timer,SIGNAL(timeout()),SLOT(showPic()));
    return timer;
}

QTimer* MainWindow::setupComputing(int i)
{
    QTimer *timer = new QTimer(this);
    timer->setInterval(i);
    connect(timer,SIGNAL(timeout()),SLOT(compute()));
    return timer;
}

void MainWindow::setupButtons()
{ // initial state; ; can create new run + can play old run
    ui->inputButton->setEnabled(false);
    ui->inputButton->hide();
    ui->computeButton->setEnabled(true);
    ui->playButton->setEnabled(true);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(false);

    setupFields();
}

void MainWindow::setupFields()
{ // initial state; ; can create new run + can play old run
    ui->z_pointsField->setText(values->value(Z_POINTS));
    ui->x_pointsField->setText(values->value(X_POINTS));
    ui->aspect_ratioField->setText(values->value(ASPECT_RATIO));
    ui->timaxField->setText(values->value(TIME_STEPS_MAX));
    ui->stp_asciiField->setText(values->value(OUTPUT_STEP));
    ui->raField->setText(values->value(RAYLEIGH));
    ui->raHField->setText(values->value(RAYLEIGH_H));
    ui->eTField->setText(values->value(VISC_CONTRAST_T));
    ui->TrefField->setText(values->value(T_REF));
    ui->eZField->setText(values->value(VISC_CONTRAST_Z));
    ui->ZrefField->setText(values->value(Z_REF));
    if(values->value(RESTART) == 0) {
        ui->RestartcheckBox->setChecked(true);
    }
    else {
        ui->RestartcheckBox->setChecked(false);
    }
}

void MainWindow::updateStatusBar(){
    statusMessageLabel->setText(status);
}

void MainWindow::onPlayClicked() // show pics; can pause + can stop
{
    status = "Gestartet";
    ui->inputButton->setEnabled(false);
    ui->computeButton->setEnabled(false);
    ui->playButton->setEnabled(false);
    ui->pauseButton->setEnabled(true);
    ui->stopButton->setEnabled(true);

    playLoop();
    updateStatusBar();
}

void MainWindow::playLoop()
{
    //after pause continue
    //after stop begin new

    if (!paused){
        // show pics from the begin
        setupPictureIterator();
    }

    paused = !paused;

    pTimer->start();
}

void MainWindow::setupPictureIterator()
{
    // std::cout << "setup\n";
    QStringList filters;
    filters << "*.jpg" << "*.png" <<"*.pdf";
    // set yacc pics directory

    std::string buffer;
    switch (ui->fieldcomboBox->currentIndex()){
    case 0 : buffer =yaccDir.toStdString() + "/Plots/temperature"; break;
    case 1 : buffer =yaccDir.toStdString() + "/Plots/viscdiss"; break;
    case 2 : buffer =yaccDir.toStdString() + "/Plots/velocity"; break;
    case 3 : buffer =yaccDir.toStdString() + "/Plots/viscosity"; break;
    case 4 : buffer =yaccDir.toStdString() + "/Plots/tempanomaly"; break;}

    QDir::setCurrent(buffer.c_str());
    QDir dir(buffer.c_str());

    QStringList filesToDisplay = dir.entryList(filters, QDir::Files, QDir::NoSort);
    numberofPics = filesToDisplay.size();
    picIter = new QStringListIterator(filesToDisplay);

}

void MainWindow::showPic()
{

    if(picIter != NULL && picIter->hasNext())
    {
        // std::cout << "show pic\n";

        QString buffer = picIter->next();

        QPixmap bufferimage = scale(QPixmap(buffer.trimmed()));



        if (previousDisplayedPic.compare(buffer) != 0 && !bufferimage.isNull()){
        ui->label->clear();
        bufferimage = scale(QPixmap(buffer.trimmed()));
        ui->label->setPixmap(bufferimage);
        // std::cout << (buffer.toStdString()) << "\n";
        previousDisplayedPic = buffer;
        ui->label->show();

        }
    }
    else {
        // std::cout << "else\n";

        if (firstrun || numberofPics < numberofFiles+1){
            setupPictureIterator();
            for (int i = 0; i<numberofPics-1; i++){
                if (picIter->next()==previousDisplayedPic){
                    break;
                }
                //picIter->next();
            }
        }
        else{
            pTimer->stop();
            firstrun = false;
            onStopClicked();
        }

        // std:: cout << "\n" << numberofPics << " " << numberofPicsOld;
        // pTimer->stop();
        // onStopClicked();
    }
}

void MainWindow::onPauseClicked() // pause pics; can play + can stop
{
    pTimer->stop();
    status = "Pausiert";
    ui->inputButton->setEnabled(false);
    ui->computeButton->setEnabled(false);
    ui->playButton->setEnabled(true);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
    updateStatusBar();
    paused = true;
}

void MainWindow::onInputClicked() // stop yacc + create input file; can run
{
    pTimer->stop();
    pTimer = setupTimer(interval);
    status = "Eingabe erfolgt";
    updateConfig();
    ui->inputButton->setEnabled(false);
    ui->computeButton->setEnabled(true);
    ui->playButton->setEnabled(false);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(false);

    updateStatusBar();
}

void MainWindow::updateConfig()
{
    storeValue(values, Z_POINTS, ui->z_pointsField->text(), VALUE_INT);
    storeValue(values, X_POINTS, ui->x_pointsField->text(), VALUE_INT);
    storeValue(values, ASPECT_RATIO, ui->aspect_ratioField->text(), VALUE_DOUBLE);
    storeValue(values, TIME_STEPS_MAX, ui->timaxField->text(), VALUE_INT);
    storeValue(values, OUTPUT_STEP, ui->stp_asciiField->text(), VALUE_INT);
    storeValue(values, RAYLEIGH, ui->raField->text(), VALUE_DOUBLE);
    storeValue(values, RAYLEIGH_H, ui->raHField->text(), VALUE_DOUBLE);
    storeValue(values, VISC_CONTRAST_T, ui->eTField->text(), VALUE_DOUBLE);
    storeValue(values, T_REF, ui->TrefField->text(), VALUE_DOUBLE);
    storeValue(values, VISC_CONTRAST_Z, ui->eZField->text(), VALUE_DOUBLE);
    storeValue(values, Z_REF, ui->ZrefField->text(), VALUE_DOUBLE);

    QString boolbuffer = "";
    if(ui->RestartcheckBox->isChecked()) {
        boolbuffer = "1";
        varrestart = true;
    }
    else {
        boolbuffer = "0";
        varrestart = false;
    }
    storeValue(values, RESTART, boolbuffer, VALUE_BOOL);
    //...

    yaccSettings->save(values);
}

void MainWindow::storeValue(QHash<QString,QString> *values, QString key, QString value, int type){
   // QString value = field->text();
    if (!value.isNull() && !value.isEmpty()){
        switch (type){
        case VALUE_INT:
            value = assertInt(value, key);
            break;
        case VALUE_DOUBLE:
            value = assertDouble(value, key);
            break;
        case VALUE_BOOL:
            value = assertBool(value, key);
            break;
        }

        if (!value.isNull()){
            values->insert(key, value);
        }
    }
}

QString MainWindow::assertBool(QString number, QString fieldname)
{
    // std::cout << number.trimmed().toStdString();
    if (!((number.trimmed().compare("0") == 0) || (number.trimmed().compare("1") == 0)) ){
        QMessageBox msgBox;
        msgBox.setText("Das Feld '"+fieldname+"' muss Ja oder Nein sein. (1 oder 0) Aktuell:" +number.trimmed());
        msgBox.exec();
        return NULL;
    }
    return number.trimmed();
}

QString MainWindow::assertDouble(QString number, QString fieldname)
{
    bool ok;
    number.replace("d","e");
    number.trimmed().toDouble(&ok);
    if (!ok){
        QMessageBox msgBox;
        msgBox.setText("Das Feld '"+fieldname+"' muss eine double Zahl enthalten (Punkt statt Komma)");
        msgBox.exec();
        return NULL;
    }
    number.replace("e","d");
    return number.trimmed();
}

QString MainWindow::assertInt(QString number, QString fieldname)
{
    bool ok;
    number.trimmed().toInt(&ok);

    if (!ok){
        QMessageBox msgBox;
        msgBox.setText("Das Feld '"+fieldname+"' muss eine int Zahl enthalten");
        msgBox.exec();
        return NULL;
    }
    // number.replace("e","d");
    return number.trimmed();
}

void MainWindow::onComputeClicked() // start yacc + start plots; can play + can create new run
{     
    firstrun = true;
    numberofPics = 0;
    numberofPicsOld = 0;
    numberofFiles = 0;
    numberofcurrentFiles = 0;
    yaccfinished = false;
    finished_processes = 0;
    picIter = NULL;
    fileIter = NULL;
    fileold = " ";
    processes = NULL;
    running_Processes = 0;

    finished_fields[0] = false;
    finished_fields[1] = false;
    finished_fields[2] = false;
    finished_fields[3] = false;
    finished_fields[4] = false;

    dontstop = false;
    computed = 1;
    if (ui->comboBox->currentIndex() == 0){

        bool ok1,ok2;
        values->value(TIME_STEPS_MAX).trimmed().toInt(&ok1);
        values->value(OUTPUT_STEP).trimmed().toInt(&ok2);

        if (ok1 && ok2 && values->value(OUTPUT_STEP).trimmed().toInt()!=0){
            numberofFiles = values->value(TIME_STEPS_MAX).trimmed().toInt()/values->value(OUTPUT_STEP).trimmed().toInt(); // muss noch angepasst werden!
        }
        else {
            QMessageBox msgBox;
            msgBox.setText("Die Ausgabe muss ein ganzes Vielfaches der Zeitschritte sein!");
            msgBox.exec();
            numberofFiles = 0;
        }

    pTimer->stop();
    pTimer = setupTimer(interval);
    updateConfig();

        QFile yaccinp(yaccDir+"/yacc.inp");
        yaccinp.remove();
        QFile::copy(yaccDir +"/yacc.easy", yaccDir +"/yacc.inp");
    }
    else {

        QFile yaccadvanced(yaccDir+"/yacc.advanced");
        yaccadvanced.remove();

        QFile outfile;
        outfile.setFileName(yaccDir +"/yacc.advanced");
        outfile.open(QIODevice::Append);
        QTextStream out(&outfile);
        out << ui->textEdit->toPlainText() << endl;


        QFile yaccinp(yaccDir+"/yacc.inp");
        yaccinp.remove();
        QFile::copy(yaccDir +"/yacc.advanced", yaccDir +"/yacc.inp");

        yaccSettings->setFile(yaccDir + "/yacc.advanced");
        values = yaccSettings->read();


        bool ok1,ok2;
        values->value(TIME_STEPS_MAX).trimmed().toInt(&ok1);
        values->value(OUTPUT_STEP).trimmed().toInt(&ok2);

        if (ok1 && ok2 && values->value(OUTPUT_STEP).trimmed().toInt()!=0){
            numberofFiles = values->value(TIME_STEPS_MAX).trimmed().toInt()/values->value(OUTPUT_STEP).trimmed().toInt(); // muss noch angepasst werden!
        }
        else {
            QMessageBox msgBox;
            msgBox.setText("Die Ausgabe muss ein ganzes Vielfaches der Zeitschritte sein!");
            msgBox.exec();
            numberofFiles = 0;
        }

        yaccSettings->setFile(yaccDir + "/yacc.easy");
        values = yaccSettings->read();
    }

    ui->inputButton->setEnabled(false);
    ui->computeButton->setEnabled(false);
    ui->playButton->setEnabled(false);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(false);

    status = "Yacc bearbeitet die Eingaben";
    updateStatusBar();

    QObject *parent;
    QProcess *process1 = new QProcess(parent);

    // set yacc directory
    QDir::setCurrent(yaccDir);
    QDir ydir(yaccDir);

    // remove existing files
    if (!varrestart){
    deleteFiles(ydir, "*.dat");
    }

    // choose between text edit and gui edit
    // copy yaac.easy or yacc.advanced into yacc.imp

    // start yacc
    process1->connect(process1, SIGNAL(finished(int, QProcess::ExitStatus)),this, SLOT(onYaccProcessFinished(int, QProcess::ExitStatus)));
    process1->start("./yacc");

    // set Pics directory
    QString picsPath = "Plots";
    QDir picsDir;
    // picsDir.mkdir(picsPath);
    QDir::setCurrent(picsDir.canonicalPath() + "/Plots");

    std::string buffer;
    switch (ui->fieldcomboBox->currentIndex()){
    case 0: buffer ="temperature"; break;
    case 1: buffer ="viscdiss"; break;
    case 2: buffer ="velocity"; break;
    case 3: buffer ="viscosity"; break;
    case 4: buffer ="tempanomaly"; break;}

    // picsDir.mkdir(buffer.c_str());
    QDir::setCurrent(yaccDir);
    QDir pDir(picsDir.canonicalPath());

    // remove existing files
    if (!varrestart){
        QObject *parent;
        QProcess *process2 = new QProcess(parent);
        process2->start("rm -r Plots");
        process2->waitForFinished(-1);

    }
    // start plots
    std::cout<<"starting the cTimer\n";
    cTimer->start();

    ui->inputButton->setEnabled(true);
    ui->computeButton->setEnabled(true);
    ui->playButton->setEnabled(false);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
    status = "Bilder werden erstellt";
    updateStatusBar();

    pTimer->start();

}

void MainWindow::setupFileIterator(){
    QStringList filters1;
    filters1 << "grd_*_.dat";
    QStringList filters2;
    filters2 << "profiles_*_.dat";

    QDir graf (yaccDir);
    QStringList filesToCompute = graf.entryList(filters1, QDir::Files, QDir::Name);
    QStringList filesReadyToCompute = graf.entryList(filters2,  QDir::Files, QDir::Name);


    checkIter = new QStringListIterator(filesReadyToCompute);
    fileIter = new QStringListIterator(filesToCompute);

    numberofCheckFiles = filesReadyToCompute.length();
    numberofcurrentFiles = filesToCompute.length();
}


void MainWindow::onProcessFinished(int exitcode, QProcess::ExitStatus exitstatus){

    finished_processes++;
    running_Processes--;
    if(finished_processes > numberofFiles || numberofFiles == numberofPics){
        status = "Alle Bilder berechnet";
        updateStatusBar();
        firstrun = false;
        pTimer->stop();
        setupPictureIterator();
        showPic();
        ui->playButton->setEnabled(true);
        ui->pauseButton->setEnabled(false);
        ui->stopButton->setEnabled(false);
        // delete processes;
    }
}

void MainWindow::onYaccProcessFinished(int exitcode, QProcess::ExitStatus exitstatus){
    std::cout << "yacc finished!\n";
    QFile yaccinp(yaccDir+"/yacc.inp");
    yaccinp.remove();
    QFile::copy(yaccDir +"/yacc.advanced", yaccDir +"/yacc.inp");

    threads++;
    yaccfinished = true;
}

void MainWindow::compute()
{

    // threads = values->find(KEY_THREADS).value().toInt();
    int rows = 0;
    bool ok;

    QString filename = yaccDir + "/timeseries.dat";
    QFile timeseries(filename);
    if (!timeseries.open(QIODevice::ReadOnly | QIODevice::Text)){
        std::cout << "cant open: " << filename.toStdString() << "\n";
    }
    else{
        QTextStream in(&timeseries);
        while (!in.atEnd()){
            in.readLine();
            rows++;
            ui->lSteps->setText(QString::number(rows-2));
        }
    }

    if (fileIter != NULL && fileIter->hasNext() && (running_Processes < threads-1)){
        QString arguments;
        QString file, checkfile;

        file = fileIter->next();
        file.remove("grd_");
        file.remove("_.dat");

        // std::cout << file.toInt(&ok) << " rows: " << rows <<"\n";

        arguments = "csh 2d_plots.csh " +file;
        switch (ui->fieldcomboBox->currentIndex()){
        case 0: arguments+=" temperature";
                break;
        case 1: arguments+=" viscdiss";
                break;
        case 2: arguments+=" velocity";
                break;
        case 3: arguments+=" viscosity";
                break;
        case 4: arguments+=" tempanomaly";
                break;}

        // std::cout << arguments.toStdString() << "\n";

        bool computable= false;
        if (rows-2>file.toInt(&ok) || yaccfinished){
            computable = true;
        }
        else {
            // std::cout << "previous file!\n";
            fileIter->previous();
        }


        // std::cout << fileold.compare(file)  << " compared!\n";

        if (fileold.compare(file) != 0 && computable) {
            QObject *parent;
            processes = new QProcess(parent);
            fileold = file;
            QDir GraphicsDir = (yaccGraphicsDir);
            QDir::setCurrent(GraphicsDir.canonicalPath());
            // std::cout << GraphicsDir.canonicalPath().toStdString() << " " << arguments.toStdString() << "\n";
            processes->connect(processes, SIGNAL(finished(int, QProcess::ExitStatus)),this, SLOT(onProcessFinished(int, QProcess::ExitStatus)));
            processes->connect(processes,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()));
            processes->connect(processes,SIGNAL(readyReadStandardError()),this,SLOT(readyReadStandardError()));
            processes->start(arguments);
            running_Processes++;
            computed++;
            std::cout << "Process " << computed-1 << " started: " << arguments.toStdString() << " running: " << running_Processes << "\n";
        }
        //if ((running_Processes+1 > threads)){
           // std::cout << "isRunning!\n";
          //  isRunning = true;
        //}
        // else {
            // std::cout << "is not Running! computed: " << computed <<"\n";
           // isRunning = false;
        // }
    }
    else{
        if (numberofcurrentFiles < numberofFiles+1) {
            setupFileIterator();
            for (int i = 0; i<computed-1; i++){
                fileIter->next();
                checkIter->next();
            }
        }
        if(computed > numberofFiles+1){
            std::cout << "cTimer stopped\n";

            finished_fields[ui->fieldcomboBox->currentIndex()] = true;

            cTimer->stop();
        }
    }
}


void MainWindow::deleteFiles(QDir dir, QString filter)
{
    QStringList filters;
    filters << filter; //"*.dat" ;

    QStringList filesToDelete = dir.entryList(filters, QDir::Files, QDir::NoSort);
    QStringList::iterator iter;
    for (iter = filesToDelete.begin(); iter != filesToDelete.end(); ++iter){
        dir.remove(*iter);
    }
}

void MainWindow::onStopClicked() // stop pics;
{
    pTimer->stop();
    cTimer->stop();

    status = "Gestoppt";
    setupButtons();

    if(firstrun){
        QMessageBox msgBox;
        msgBox.setText("Die Berechnung der Bilder wurde unterbrochen!");
        msgBox.exec();
        ui->playButton->setEnabled(false);
    }

    ui->label->setStyleSheet("QLabel { background-color : white}");
    updateStatusBar();
    pTimer = setupTimer(interval);
    paused = false;
}

void MainWindow::readConfig()
{
    GUISettings *guiSettings = new GUISettings();
    guiSettings->setFile("config.txt");
    QHash<QString, QString> *values = guiSettings->read();

    yaccDir = values->find(KEY_PATH).value();
    advanced = values->find(KEY_ADVANCED).value().toInt();
    yaccGraphicsDir = values->find(GRAPHICS_PATH).value();
    interval = values->find(KEY_INTERVAL).value().toInt();
    threads = values->find(KEY_THREADS).value().toInt();
}

void MainWindow::setupView()
{

    //Dummy-Bild für Anfang einblenden

//    QPixmap image(yaccDir + "/testbild_breit.png");
//    image = scale(image);
//    ui->label->setPixmap(image);
//    ui->label->show();
}

QPixmap MainWindow::scale(QPixmap image)
{
    int viewWidth, viewHeigth;
    int imgWidth, imgHeigth;

    viewHeigth = ui->label->geometry().height();
    viewWidth = ui->label->geometry().width();

    imgWidth = image.width();
    imgHeigth = image.height();

    QPixmap scaledImage = image;

    if (!scaledImage.isNull()){
        scaledImage = image.scaled(viewWidth-2, viewHeigth-2, Qt::KeepAspectRatio);
    }
    return scaledImage;
}

void MainWindow::on_fieldcomboBox_currentIndexChanged(int index)
{
    setupPictureIterator();

    std::cout << "numberofPics: " << numberofPics << " numberofFiles: " << numberofFiles << "\n";
    if (finished_fields[index] == false){

    firstrun = true;
    numberofPics = 0;
    // numberofFiles = 0;
    numberofcurrentFiles = 0;
    numberofPicsOld = 0;
    yaccfinished = true;
    finished_processes = 0;
    picIter = NULL;
    fileIter = NULL;
    fileold = " ";
    processes = NULL;
    dontstop = false;
    computed = 1;
    running_Processes = 0;

    // start plots
    std::cout<<"starting the cTimer\n";
    cTimer->start();

    ui->inputButton->setEnabled(true);
    ui->computeButton->setEnabled(true);
    ui->playButton->setEnabled(false);
    ui->pauseButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
    status = "Bilder werden erstellt";
    updateStatusBar();

    pTimer->start();
    }
    else{
        showPic();
    }

}


void MainWindow::readyReadStandardOutput(){
    char *buffer = processes->readAllStandardOutput().data();
    // std::cout << buffer << "\n";
}

void MainWindow::readyReadStandardError(){
    char *buffer = processes->readAllStandardOutput().data();
   //  std::cout << buffer << "\n";
}

void MainWindow::on_previousButton_clicked()
{
    if(picIter != NULL && picIter->hasPrevious())
    {
        QString buffer = picIter->previous();
        if (!lastclicked && picIter->hasNext()){
            buffer = picIter->previous();
        }
        QPixmap bufferimage = scale(QPixmap(buffer.trimmed()));
        ui->label->clear();
        bufferimage = scale(QPixmap(buffer.trimmed()));
        ui->label->setPixmap(bufferimage);
        ui->label->show();
        lastclicked = true;
    }

}

void MainWindow::on_nextButton_clicked()
{
    if(picIter != NULL && picIter->hasNext())
    {
        if (lastclicked){
            picIter->next();
        }
        showPic();
        lastclicked = false;
    }
}

void MainWindow::on_firstButton_clicked()
{
    if (picIter != NULL && picIter->hasPrevious()){
    picIter->toFront();
    showPic();
    }
}

void MainWindow::on_lastButton_clicked()
{
    if (picIter != NULL && picIter->hasNext()){
    picIter->toBack();
    picIter->previous();
    showPic();
    }
}

void MainWindow::on_pushButton_clicked()
{
    if (ui->aspect_ratioField->isHidden()){
        ui->aspect_ratioField->show();
        ui->label_9->show();
        ui->z_pointsField->show();
        ui->label_2->show();
        ui->x_pointsField->show();
        ui->label_12->show();
    }
    else {
        ui->aspect_ratioField->hide();
        ui->label_9->hide();
        ui->z_pointsField->hide();
        ui->label_2->hide();
        ui->x_pointsField->hide();
        ui->label_12->hide();
    }
}

void MainWindow::on_viscosityButton_clicked()
{
    if (ui->eTField->isHidden()){
        ui->eTField->show();
        ui->label_7->show();
        ui->TrefField->show();
        ui->label_10->show();
        ui->eZField->show();
        ui->label_8->show();
        ui->ZrefField->show();
        ui->label_11->show();
    }
    else {
        ui->eTField->hide();
        ui->label_7->hide();
        ui->TrefField->hide();
        ui->label_10->hide();
        ui->eZField->hide();
        ui->label_8->hide();
        ui->ZrefField->hide();
        ui->label_11->hide();
    }
}

void MainWindow::on_rayleighButton_clicked()
{
    if (ui->raField->isHidden()){
        ui->raField->show();
        ui->raHField->show();
        ui->label_5->show();
        ui->label_6->show();
    }
    else {
        ui->raField->hide();
        ui->raHField->hide();
        ui->label_5->hide();
        ui->label_6->hide();
    }
}

void MainWindow::on_actionBeenden_triggered()
{
    MainWindow::close();
}

void MainWindow::on_actionEigenschaften_triggered()
{
    QDir backupDir = QDir::currentPath();
    QDir::setCurrent(startingDir.canonicalPath());
    setup = new SettingsDialog(this);
    setup->exec();
    readConfig();
    QDir::setCurrent(backupDir.canonicalPath());

    if (advanced == 0) {
        ui->comboBox->hide();
    }
    else {
        ui->comboBox->show();
    }

    ui->comboBox->setCurrentIndex(0);

    pTimer = setupTimer(interval);
}


void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    if (index == 0){

        QFile yacceasy(yaccDir+"/yacc.easy");
        yacceasy.remove();

        QFile outfile;
        outfile.setFileName(yaccDir +"/yacc.easy");
        outfile.open(QIODevice::Append);
        QTextStream out(&outfile);
        out << ui->textEdit->toPlainText() << endl;
        outfile.close();

        QFile yaccadvanced(yaccDir+"/yacc.advanced");
        yaccadvanced.remove();

        QFile outfile2;
        outfile2.setFileName(yaccDir +"/yacc.advanced");
        outfile2.open(QIODevice::Append);
        QTextStream out2(&outfile2);
        out2 << ui->textEdit->toPlainText() << endl;
        outfile2.close();

        yaccSettings->setFile(yaccDir + "/yacc.easy");
        values = yaccSettings->read();
        setupFields();
        updateConfig();

        ui->textEdit->hide();

        for (int i = 0 ; (ui->gridLayout->count() > i); i++){
            ui->gridLayout->itemAt(i)->widget()->show();
        }
        ui->inputButton->hide();
        // rest show
    }
    else{
        ui->textEdit->show();
        const QString file2(yaccDir +"/yacc.advanced");
        QFile file(file2);
        QString content;
        bool ret = file.open(QIODevice::ReadOnly | QIODevice::Text);
        if( ret )
        {
            std::cout << "TEXT\n";
            QTextStream stream(&file);
            content = stream.readAll();
        }

        ui->textEdit->setText(content);
        ui->textEdit->update();

        for (int i = 0 ; (ui->gridLayout->count() > i); i++){
            ui->gridLayout->itemAt(i)->widget()->hide();
        }

    }
}
